import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {Observable} from 'rxjs';

@Component({
  selector: 'ng-tools-step-line',
  templateUrl: './step-line.component.html',
  styleUrls: ['./step-line.component.scss']
})
export class StepLineComponent implements OnInit {
  @Input() steps: {
    title: string;
    cssIcon: string;
    canLeave?: (index: number, targetIndex: number) => Observable<any>; // 检查是否能够离开当前步骤
  }[];
  @Input() currentStep;
  @Output() stepChanged = new EventEmitter();
  @Output() leaveCheckFailed = new EventEmitter();


  constructor() {
  }

  ngOnInit() {
    if (!this.currentStep) {
      this.currentStep = 0;
    }
  }

  goTo(index: number, step: any) {
    if (this.currentStep !== index) {
      if (this.steps[this.currentStep].canLeave) {
        if (typeof this.steps[this.currentStep].canLeave === 'function') {
          this.steps[this.currentStep].canLeave(this.currentStep, index)
            .subscribe((result) => {
              if (result) {
                this.stepChanged.emit({targetIndex: index, targetStep: step});
                this.currentStep = index;
              }
            }, error => {
              this.leaveCheckFailed.emit(error);
            });
        } else {
          throw Error('canLeave is not a function');
        }
      } else {
        this.stepChanged.emit({targetIndex: index, targetStep: step});
        this.currentStep = index;
      }
    }
  }

}
